"""
Pydantic 数据验证模型
"""
from typing import Optional, Dict, List, Any, Union
from datetime import datetime
from pydantic import BaseModel, Field, field_validator, model_validator
from uuid import UUID
from enum import Enum


# ============================================================================
# 枚举定义
# ============================================================================

class ObjectType(str, Enum):
    """对象类型枚举"""
    OBSERVATION_EQUIPMENT = "observation_equipment"  # 观测装备
    INFRASTRUCTURE = "infrastructure"  # 基础设施
    SEA_TARGET = "sea_target"  # 海上目标
    LAND_TARGET = "land_target"  # 陆上目标


class DeploymentStatus(str, Enum):
    """部署状态枚举"""
    DEPLOYED = "已部署"
    PENDING = "待部署"
    MAINTENANCE = "维护中"
    RETIRED = "退役"


class EquipmentCategoryObservation(str, Enum):
    """观测装备类别枚举"""
    RADAR = "radar"
    OPTICAL = "optical"
    SONAR = "sonar"
    ELINT = "elint"
    SATELLITE = "satellite"
    UAV = "uav"

    @classmethod
    def get_label(cls, value):
        """获取中文标签"""
        labels = {
            "radar": "雷达",
            "optical": "光学",
            "sonar": "声纳",
            "elint": "电子侦察",
            "satellite": "卫星",
            "uav": "无人机"
        }
        return labels.get(value, value)


class EquipmentCategorySea(str, Enum):
    """海上目标类别枚举"""
    AIRCRAFT_CARRIER = "aircraft_carrier"
    DESTROYER = "destroyer"
    CRUISER = "cruiser"
    FRIGATE = "frigate"
    SUBMARINE = "submarine"
    AMPHIBIOUS_SHIP = "amphibious_ship"
    MERCHANT_SHIP = "merchant_ship"
    FISHING_VESSEL = "fishing_vessel"

    @classmethod
    def get_label(cls, value):
        """获取中文标签"""
        labels = {
            "aircraft_carrier": "航母",
            "destroyer": "驱逐舰",
            "cruiser": "巡洋舰",
            "frigate": "护卫舰",
            "submarine": "潜艇",
            "amphibious_ship": "两栖舰",
            "merchant_ship": "商船",
            "fishing_vessel": "渔船"
        }
        return labels.get(value, value)


class EquipmentCategoryInfrastructure(str, Enum):
    """基础设施类别枚举"""
    AIRPORT = "airport"
    SEAPORT = "seaport"
    POWER_STATION = "power_station"
    OIL_FIELD = "oil_field"
    TRAIN_STATION = "train_station"

    @classmethod
    def get_label(cls, value):
        """获取中文标签"""
        labels = {
            "airport": "机场",
            "seaport": "港口",
            "power_station": "电站",
            "oil_field": "油田",
            "train_station": "火车站"
        }
        return labels.get(value, value)


class EquipmentCategoryLand(str, Enum):
    """陆上目标类别枚举"""
    BRIDGE = "bridge"
    ROAD = "road"
    RAILWAY = "railway"
    TUNNEL = "tunnel"
    DAM = "dam"
    INDUSTRIAL_AREA = "industrial_area"
    RESIDENTIAL_AREA = "residential_area"
    MILITARY_FACILITY = "military_facility"

    @classmethod
    def get_label(cls, value):
        """获取中文标签"""
        labels = {
            "bridge": "桥梁",
            "road": "道路",
            "railway": "铁路",
            "tunnel": "隧道",
            "dam": "水坝",
            "industrial_area": "工业区",
            "residential_area": "居民区",
            "military_facility": "军事设施"
        }
        return labels.get(value, value)


# ============================================================================
# 类型特定数据模型
# ============================================================================

# 观测装备类别特定数据模型
class RadarSpecificData(BaseModel):
    """雷达装备专属字段"""
    scan_rate: Optional[float] = Field(None, description="扫描速率(rpm)")
    power_output: Optional[float] = Field(None, description="功率输出(kW)")
    detection_modes: Optional[List[str]] = Field(None, description="探测模式")
    environmental_tolerance: Optional[Dict[str, Any]] = Field(None, description="环境耐受性")
    platform_type: Optional[str] = Field(None, description="平台类型")
    tracking_capacity: Optional[int] = Field(None, description="同时跟踪目标数")
    operating_frequency: Optional[str] = Field(None, description="工作频率")
    frequency_range: Optional[str] = Field(None, description="频率范围")


class OpticalSpecificData(BaseModel):
    """光学装备专属字段"""
    focal_length: Optional[float] = Field(None, description="焦距(mm)")
    field_of_view: Optional[str] = Field(None, description="视场角")
    resolution: Optional[str] = Field(None, description="分辨率")
    sensor_type: Optional[str] = Field(None, description="传感器类型")
    spectral_bands: Optional[List[str]] = Field(None, description="光谱波段")


class SonarSpecificData(BaseModel):
    """声纳装备专属字段"""
    acoustic_power: Optional[float] = Field(None, description="声功率")
    beam_width: Optional[str] = Field(None, description="波束宽度")
    frequency: Optional[str] = Field(None, description="工作频率")
    detection_range: Optional[float] = Field(None, description="探测距离(km)")


class ElintSpecificData(BaseModel):
    """电子侦察装备专属字段"""
    frequency_range: Optional[str] = Field(None, description="频率范围")
    sensitivity: Optional[str] = Field(None, description="灵敏度")
    signal_types: Optional[List[str]] = Field(None, description="信号类型")
    detection_modes: Optional[List[str]] = Field(None, description="探测模式")


class SatellitePayload(BaseModel):
    """卫星载荷配置"""
    type: str = Field(..., description="载荷类型")
    resolution: str = Field(..., description="分辨率")
    swath: str = Field(..., description="幅宽")


class SatelliteSpecificData(BaseModel):
    """卫星装备专属字段"""
    # 基本信息
    name: Optional[str] = Field(None, description="卫星名称")
    status: Optional[str] = Field(None, description="运行状态")
    active: Optional[bool] = Field(True, description="是否活跃")

    # 轨道参数
    orbit_type: Optional[str] = Field(None, description="轨道类型")
    altitude: Optional[float] = Field(None, description="轨道高度(km)")
    orbit_period: Optional[str] = Field(None, description="轨道周期")
    coverage: Optional[float] = Field(None, description="覆盖范围(km²)")

    # 性能参数
    resolution: Optional[float] = Field(None, description="分辨率(m)")
    revisit_period: Optional[str] = Field(None, description="重访周期")

    # 载荷配置
    payload: Optional[List[SatellitePayload]] = Field(None, description="载荷配置列表")

    # 通信参数
    band: Optional[str] = Field(None, description="波段")
    bandwidth: Optional[str] = Field(None, description="带宽")

    # 状态监控
    battery: Optional[str] = Field(None, description="电量百分比")
    fuel: Optional[str] = Field(None, description="燃料百分比")
    current_position: Optional[str] = Field(None, description="当前位置坐标")

    # 其他信息
    launch_time: Optional[str] = Field(None, description="发射时间")
    typical_usage: Optional[str] = Field(None, description="典型用途")


class UavSpecificData(BaseModel):
    """无人机装备专属字段"""
    endurance_time: Optional[float] = Field(None, description="续航时间(小时)")
    max_altitude: Optional[float] = Field(None, description="最大飞行高度(m)")
    payload_type: Optional[str] = Field(None, description="载荷类型")
    control_range: Optional[float] = Field(None, description="控制距离(km)")


# 基础设施类别特定数据模型
class InfrastructureCommonData(BaseModel):
    """基础设施通用字段"""
    coordinates: Optional[str] = Field(None, description="当前位置坐标(经度,纬度)")
    importance: Optional[str] = Field(None, description="重要程度: general(一般) / important(重要)")
    discovery_time: Optional[datetime] = Field(None, description="发现时间")


class AirportSpecificData(InfrastructureCommonData):
    """机场专属字段"""
    area: Optional[float] = Field(None, description="占地面积(㎡)")
    runway_length: Optional[float] = Field(None, description="跑道长度(m)")
    runway_width: Optional[float] = Field(None, description="跑道宽度(m)")
    runway_count: Optional[int] = Field(None, description="跑道数量")
    runway_surface: Optional[str] = Field(None, description="跑道表面材料")
    altitude: Optional[float] = Field(None, description="海拔(m)")
    capacity: Optional[float] = Field(None, description="容量(架次/天)")
    usage_type: Optional[str] = Field(None, description="使用性质")
    usage_time: Optional[str] = Field(None, description="使用时间")


class SeaportSpecificData(InfrastructureCommonData):
    """港口专属字段"""
    area: Optional[float] = Field(None, description="占地面积(㎡)")
    berth_count: Optional[int] = Field(None, description="泊位数量")
    max_vessel_tonnage: Optional[float] = Field(None, description="最大停靠吨位")
    usage_type: Optional[str] = Field(None, description="使用性质")
    water_depth: Optional[float] = Field(None, description="水深(m)")


class PowerStationSpecificData(InfrastructureCommonData):
    """电站专属字段"""
    area: Optional[float] = Field(None, description="占地面积(㎡)")
    power_generation: Optional[float] = Field(None, description="发电量(MW)")
    fuel_type: Optional[str] = Field(None, description="燃料类型")
    capacity: Optional[float] = Field(None, description="容量(MW)")
    construction_year: Optional[int] = Field(None, description="建设年份")


class OilFieldSpecificData(InfrastructureCommonData):
    """油田专属字段"""
    area: Optional[float] = Field(None, description="占地面积(㎡)")
    oil_production_rate: Optional[float] = Field(None, description="日产量(桶/天)")
    oil_reserves: Optional[float] = Field(None, description="储量(桶)")
    capacity: Optional[float] = Field(None, description="容量")
    well_count: Optional[int] = Field(None, description="油井数量")
    discovery_time: Optional[str] = Field(None, description="发现时间")
    exploitation_time: Optional[str] = Field(None, description="开采时间")
    total_reserves: Optional[str] = Field(None, description="总储量")
    annual_output: Optional[str] = Field(None, description="年产量")
    oilfield_area: Optional[str] = Field(None, description="油田面积")
    main_production_layer: Optional[str] = Field(None, description="主产油层")


class TrainStationSpecificData(InfrastructureCommonData):
    """火车站专属字段"""
    station_type: Optional[str] = Field(None, description="车站类型")
    platform_count: Optional[int] = Field(None, description="站台数量")
    daily_trains: Optional[int] = Field(None, description="日均列车班次")
    passenger_capacity: Optional[int] = Field(None, description="日均客流量(人次)")
    freight_capacity: Optional[float] = Field(None, description="货运能力(万吨/年)")




# 海上目标类别特定数据模型
class SeaTargetCommonData(BaseModel):
    """海上目标通用字段"""
    coordinates: Optional[str] = Field(None, description="当前位置坐标(经度,纬度)")
    importance: Optional[str] = Field(None, description="重要程度: general(一般) / important(重要)")
    discovery_time: Optional[datetime] = Field(None, description="发现时间")


class AircraftCarrierSpecificData(SeaTargetCommonData):
    """航母专属字段"""
    displacement: Optional[float] = Field(None, description="排水量(吨)")
    length: Optional[float] = Field(None, description="长度(m)")
    beam: Optional[float] = Field(None, description="宽度(m)")
    draft: Optional[float] = Field(None, description="吃水(m)")
    max_speed: Optional[float] = Field(None, description="最大航速(节)")
    cruise_speed: Optional[float] = Field(None, description="巡航速度(节)")
    endurance: Optional[float] = Field(None, description="续航力(海里)")
    crew_capacity: Optional[int] = Field(None, description="人员数量")
    aircraft_capacity: Optional[float] = Field(None, description="最大载机数量")
    aircraft_capacity_text: Optional[str] = Field(None, description="载机数量描述")
    flight_deck_info: Optional[str] = Field(None, description="飞行甲板信息")
    propulsion_type: Optional[str] = Field(None, description="推进系统类型")
    armament: Optional[Dict[str, Any]] = Field(None, description="武器系统")
    armament_text: Optional[str] = Field(None, description="武器系统文本描述")
    sensors: Optional[List[str]] = Field(None, description="传感器列表")
    construction_year: Optional[int] = Field(None, description="建造年份")
    service_start_time: Optional[str] = Field(None, description="服役开始时间")
    home_port: Optional[str] = Field(None, description="母港")
    production_date: Optional[str] = Field(None, description="生产日期")


class WarshipSpecificData(SeaTargetCommonData):
    """军用舰船通用专属字段"""
    displacement: Optional[float] = Field(None, description="排水量(吨)")
    length: Optional[float] = Field(None, description="长度(m)")
    beam: Optional[float] = Field(None, description="宽度(m)")
    draft: Optional[float] = Field(None, description="吃水(m)")
    max_speed: Optional[float] = Field(None, description="最大航速(节)")
    cruise_speed: Optional[float] = Field(None, description="巡航速度(节)")
    endurance: Optional[float] = Field(None, description="续航力(海里)")
    crew_capacity: Optional[int] = Field(None, description="人员数量")
    propulsion_type: Optional[str] = Field(None, description="推进系统类型")
    armament: Optional[Dict[str, Any]] = Field(None, description="武器系统")
    armament_text: Optional[str] = Field(None, description="武器系统文本描述")
    sensors: Optional[List[str]] = Field(None, description="传感器列表")
    construction_year: Optional[int] = Field(None, description="建造年份")
    service_start_time: Optional[str] = Field(None, description="服役开始时间")
    home_port: Optional[str] = Field(None, description="母港")
    imo_number: Optional[str] = Field(None, description="IMO编号")
    mmsi: Optional[str] = Field(None, description="MMSI编号")
    production_date: Optional[str] = Field(None, description="生产日期")


class MerchantShipSpecificData(SeaTargetCommonData):
    """商船专属字段"""
    displacement: Optional[float] = Field(None, description="排水量(吨)")
    length: Optional[float] = Field(None, description="长度(m)")
    beam: Optional[float] = Field(None, description="宽度(m)")
    draft: Optional[float] = Field(None, description="吃水(m)")
    max_speed: Optional[float] = Field(None, description="最大航速(节)")
    crew_capacity: Optional[int] = Field(None, description="人员数量")
    cargo_capacity: Optional[float] = Field(None, description="载货量(吨)")
    cargo_type: Optional[str] = Field(None, description="货物类型")
    propulsion_type: Optional[str] = Field(None, description="推进系统类型")
    imo_number: Optional[str] = Field(None, description="IMO编号")
    mmsi: Optional[str] = Field(None, description="MMSI编号")
    home_port: Optional[str] = Field(None, description="船籍港")
    production_date: Optional[str] = Field(None, description="生产日期")


# 陆上目标类别特定数据模型
class LandTargetCommonData(BaseModel):
    """陆上目标通用字段"""
    coordinates: Optional[str] = Field(None, description="当前位置坐标(经度,纬度)")
    importance: Optional[str] = Field(None, description="重要程度: general(一般) / important(重要)")
    discovery_time: Optional[datetime] = Field(None, description="发现时间")


class BridgeSpecificData(LandTargetCommonData):
    """桥梁专属字段"""
    length: Optional[float] = Field(None, description="长度(m)")
    width: Optional[float] = Field(None, description="宽度(m)")
    max_height: Optional[float] = Field(None, description="最大高度(m)")
    load_capacity: Optional[float] = Field(None, description="载重量(吨)")
    construction_material: Optional[str] = Field(None, description="建筑材料")
    bridge_type: Optional[str] = Field(None, description="桥梁类型")
    construction_year: Optional[int] = Field(None, description="建设年份")


class IndustrialAreaSpecificData(LandTargetCommonData):
    """工业区专属字段"""
    area: Optional[float] = Field(None, description="占地面积(㎡)")
    building_count: Optional[int] = Field(None, description="建筑物数量")
    industry_type: Optional[str] = Field(None, description="工业类型")
    power_generation: Optional[float] = Field(None, description="发电量(kW)")
    water_supply: Optional[float] = Field(None, description="供水量(吨/天)")
    personnel_capacity: Optional[int] = Field(None, description="人员容量")
    vehicle_capacity: Optional[int] = Field(None, description="车辆容量")
    fuel_storage: Optional[float] = Field(None, description="燃料储存量(升)")
    construction_year: Optional[int] = Field(None, description="建设年份")


class MilitaryFacilitySpecificData(LandTargetCommonData):
    """军事设施专属字段"""
    site_area: Optional[float] = Field(None, description="占地面积(㎡)")
    building_area: Optional[float] = Field(None, description="建筑面积(㎡)")
    main_function: Optional[str] = Field(None, description="主要功能")
    construction_year: Optional[int] = Field(None, description="建设年份")


# ============================================================================
# 装备类别映射和验证
# ============================================================================

def get_equipment_category_mapping():
    """获取装备类别映射"""
    return {
        "observation_equipment": {
            "radar": RadarSpecificData,
            "optical": OpticalSpecificData,
            "sonar": SonarSpecificData,
            "elint": ElintSpecificData,
            "satellite": SatelliteSpecificData,
            "uav": UavSpecificData,
        },
        "infrastructure": {
            "airport": AirportSpecificData,
            "seaport": SeaportSpecificData,
            "power_station": PowerStationSpecificData,
            "oil_field": OilFieldSpecificData,
            "train_station": TrainStationSpecificData,
        },
        "sea_target": {
            "aircraft_carrier": AircraftCarrierSpecificData,
            "destroyer": WarshipSpecificData,
            "cruiser": WarshipSpecificData,
            "frigate": WarshipSpecificData,
            "submarine": WarshipSpecificData,
            "amphibious_ship": WarshipSpecificData,
            "merchant_ship": MerchantShipSpecificData,
            "fishing_vessel": MerchantShipSpecificData,
        },
        "land_target": {
            "bridge": BridgeSpecificData,
            "road": dict,
            "railway": dict,
            "tunnel": dict,
            "dam": dict,
            "industrial_area": IndustrialAreaSpecificData,
            "residential_area": dict,
            "military_facility": MilitaryFacilitySpecificData,
        },
    }


def validate_equipment_category(object_type: str, equipment_category: str) -> bool:
    """验证装备类别是否与对象类型匹配"""
    mapping = get_equipment_category_mapping()
    return equipment_category in mapping.get(object_type, {})


def get_specific_data_model(object_type: str, equipment_category: str):
    """获取特定数据模型"""
    mapping = get_equipment_category_mapping()
    return mapping.get(object_type, {}).get(equipment_category, dict)


# ============================================================================
# 主模型
# ============================================================================

class SituationObjectBase(BaseModel):
    """态势对象基础模型"""
    object_type: ObjectType = Field(..., description="对象类型")
    equipment_category: Optional[str] = Field(None, max_length=100, description="装备类别")
    name: str = Field(..., max_length=200, description="态势对象名称")
    code: Optional[str] = Field(None, max_length=100, description="唯一编码")
    description: Optional[str] = Field(None, max_length=500, description="对象描述")
    model: Optional[str] = Field(None, max_length=200, description="型号")
    organization: Optional[str] = Field(None, max_length=300, description="所属单位")
    deployment_status: Optional[DeploymentStatus] = Field(None, description="部署状态")

    # 通用性能指标
    detection_range: Optional[float] = Field(None, description="探测距离(km)")
    response_time: Optional[float] = Field(None, description="响应时间(秒)")
    accuracy: Optional[float] = Field(None, ge=0, le=100, description="精度(%)")

    # 能力维度（改为VARCHAR，支持手动填入）
    perception_capability: Optional[str] = Field(None, max_length=200, description="感知能力详情")
    communication_capability: Optional[str] = Field(None, max_length=200, description="通信能力详情")

    # 适用场景（改为VARCHAR，支持手动填入）
    applicable_scenarios: Optional[str] = Field(None, max_length=200, description="适用场景列表")

    # 位置信息（改为VARCHAR，支持手动填入）
    location: Optional[str] = Field(None, max_length=200, description="地理位置信息")

    # 类型特定数据（动态验证）
    type_specific_data: Optional[Dict[str, Any]] = Field(default_factory=dict, description="类型特定扩展字段")

    # 通用扩展
    extra_metadata: Optional[Dict[str, Any]] = Field(default_factory=dict, description="元数据")
    tags: Optional[List[str]] = Field(default_factory=list, description="标签")

    @field_validator("equipment_category", mode="before")
    @classmethod
    def validate_equipment_category(cls, v, info):
        """验证装备类别"""
        if v is not None:
            object_type = info.data.get("object_type")
            if object_type and not validate_equipment_category(object_type, v):
                mapping = get_equipment_category_mapping()
                valid_categories = list(mapping.get(object_type, {}).keys())
                raise ValueError(f"无效的装备类别: {v}，对象类型 {object_type} 支持的类别: {', '.join(valid_categories)}")
        return v

    @model_validator(mode="before")
    @classmethod
    def validate_type_specific_data(cls, data):
        """验证类型特定数据"""
        if isinstance(data, dict):
            object_type = data.get("object_type")
            equipment_category = data.get("equipment_category")
            type_specific_data = data.get("type_specific_data", {})

            if object_type and equipment_category and type_specific_data:
                # 获取对应的特定数据模型
                specific_model = get_specific_data_model(object_type, equipment_category)
                if specific_model != dict:
                    try:
                        # 使用对应的模型验证数据
                        specific_model(**type_specific_data)
                    except Exception as e:
                        raise ValueError(f"类型特定数据验证失败: {str(e)}")

        return data

    @field_validator("tags", mode="before")
    @classmethod
    def validate_tags(cls, v):
        """验证标签"""
        if v is None:
            return []
        if isinstance(v, list):
            return v
        return []


class SituationObjectCreate(SituationObjectBase):
    """创建态势对象"""
    pass


class SituationObjectUpdate(BaseModel):
    """更新态势对象（所有字段可选）"""
    object_type: Optional[ObjectType] = None
    name: Optional[str] = Field(None, max_length=200)
    code: Optional[str] = Field(None, max_length=100)
    model: Optional[str] = Field(None, max_length=200)
    organization: Optional[str] = Field(None, max_length=300)
    deployment_status: Optional[DeploymentStatus] = None
    detection_range: Optional[float] = None
    response_time: Optional[float] = None
    accuracy: Optional[float] = Field(None, ge=0, le=100)
    perception_capability: Optional[str] = Field(None, max_length=200)
    communication_capability: Optional[str] = Field(None, max_length=200)
    applicable_scenarios: Optional[str] = Field(None, max_length=200)
    location: Optional[str] = Field(None, max_length=200)
    type_specific_data: Optional[Dict[str, Any]] = None
    extra_metadata: Optional[Dict[str, Any]] = None
    tags: Optional[List[str]] = None


class SituationObjectResponse(SituationObjectBase):
    """态势对象响应模型"""
    id: UUID
    created_at: datetime
    updated_at: datetime
    created_by: Optional[str] = None
    updated_by: Optional[str] = None

    class Config:
        from_attributes = True


class SituationObjectListResponse(BaseModel):
    """列表响应"""
    total: int = Field(..., description="总数")
    items: List[SituationObjectResponse] = Field(..., description="数据列表")
    page: int = Field(..., description="当前页码")
    page_size: int = Field(..., description="每页数量")


class SituationObjectFilter(BaseModel):
    """筛选条件"""
    object_type: Optional[ObjectType] = None
    equipment_category: Optional[str] = Field(None, description="装备类别")
    deployment_status: Optional[DeploymentStatus] = None
    organization: Optional[str] = None
    search: Optional[str] = Field(None, description="搜索关键字（名称、编码）")
    tags: Optional[List[str]] = None


class ImportRequest(BaseModel):
    """批量导入请求"""
    format: str = Field(..., description="文件格式: json/csv/xml/yaml")
    data: str = Field(..., description="文件内容")


class ExportRequest(BaseModel):
    """批量导出请求"""
    format: str = Field(default="json", description="导出格式: json/csv/xml/yaml")
    object_type: Optional[ObjectType] = None
    filters: Optional[Dict[str, Any]] = Field(default_factory=dict)


class StatisticsResponse(BaseModel):
    """统计信息响应"""
    total_count: int = Field(..., description="总数")
    by_type: Dict[str, int] = Field(..., description="按类型统计")
    by_status: Dict[str, int] = Field(..., description="按状态统计")
    by_organization: Dict[str, int] = Field(..., description="按单位统计")


# ============================================================================
# 辅助函数和API响应模型
# ============================================================================

class EquipmentCategoryItem(BaseModel):
    """装备类别项模型"""
    value: str = Field(..., description="英文值")
    label: str = Field(..., description="中文名称")


class EquipmentCategoryResponse(BaseModel):
    """装备类别响应模型"""
    object_type: str = Field(..., description="对象类型")
    categories: List[EquipmentCategoryItem] = Field(..., description="支持的装备类别列表")


class EquipmentCategoriesListResponse(BaseModel):
    """装备类别列表响应模型"""
    categories: List[EquipmentCategoryResponse] = Field(..., description="装备类别列表")


def get_all_equipment_categories() -> List[EquipmentCategoryResponse]:
    """获取所有对象类型及其装备类别"""
    mapping = get_equipment_category_mapping()
    labels = get_equipment_category_labels()
    result = []

    for object_type, categories in mapping.items():
        # 创建包含值和标签的装备类别项
        category_items = [
            EquipmentCategoryItem(
                value=category,
                label=labels.get(category, category)
            )
            for category in categories.keys()
        ]

        result.append(
            EquipmentCategoryResponse(
                object_type=object_type,
                categories=category_items
            )
        )

    return result


def get_equipment_categories_by_type(object_type: str) -> EquipmentCategoryResponse:
    """根据对象类型获取装备类别"""
    mapping = get_equipment_category_mapping()
    category_keys = list(mapping.get(object_type, {}).keys())

    # 获取标签映射
    labels = get_equipment_category_labels()

    # 创建包含值和标签的装备类别项
    categories = [
        EquipmentCategoryItem(
            value=category,
            label=labels.get(category, category)
        )
        for category in category_keys
    ]

    return EquipmentCategoryResponse(
        object_type=object_type,
        categories=categories
    )


def get_equipment_category_labels():
    """获取装备类别英文到中文的标签映射"""
    return {
        # 观测装备
        "radar": "雷达",
        "optical": "光学",
        "sonar": "声纳",
        "elint": "电子侦察",
        "satellite": "卫星",
        "uav": "无人机",

        # 海上目标
        "aircraft_carrier": "航空母舰",
        "destroyer": "驱逐舰",
        "cruiser": "巡洋舰",
        "frigate": "护卫舰",
        "submarine": "潜艇",
        "amphibious_ship": "两栖舰艇",
        "merchant_ship": "商船",
        "fishing_vessel": "渔船",

        # 基础设施
        "airport": "机场",
        "seaport": "港口",
        "power_station": "电站",
        "oil_field": "油田",
        "train_station": "火车站",

        # 陆上目标
        "bridge": "桥梁",
        "road": "道路",
        "railway": "铁路",
        "tunnel": "隧道",
        "dam": "水坝",
        "industrial_area": "工业区",
        "residential_area": "居民区",
        "military_facility": "军事设施",

        # 武器系统
        "missile": "导弹",
        "gun": "火炮",
        "rocket": "火箭",
        "torpedo": "鱼雷",
        "bomb": "炸弹",

        # 车辆
        "tank": "坦克",
        "armored_vehicle": "装甲车",
        "truck": "卡车",
        "jeep": "吉普车",
        "artillery": "火炮"
    }
